<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader @add="add" :arr="list"></TodoHeader>
    <TodoMain :arr="taskList" @del="del"></TodoMain>
    <TodoFooter
      @editActive="editActive"
      :active="isActive"
      @onClear="onClear"
      :arr="list"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";

import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

export default {
  data() {
    return {
      isActive: "all",
      list: JSON.parse(localStorage.getItem("list")) || [],
    };
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("list", JSON.stringify(this.list));
      },
    },
  },
  computed: {
    taskList() {
      if (this.isActive === "undone") {
        console.log(1);
        return this.list.filter((item) => !item.isDone);
      }
      if (this.isActive === "done") {
        return this.list.filter((item) => item.isDone);
      }
      return this.list;
    },
  },
  methods: {
    del(id) {
      let i = this.list.findIndex((item) => item.id === id);
      this.list.splice(i, 1);
    },
    //定义添加
    add(task_name) {
      const flag = this.list.some((item) => item.name === task_name);
      if (flag) return alert("内容重复");
      const id = this.list.length ? this.list[this.list.length - 1].id + 1 : 0;
      this.list.push({
        id,
        name: task_name,
        isDone: false,
      });
    },
    //清楚已完成
    onClear(undone) {
      this.list = undone;
    },
    editActive(active) {
      this.isActive = active;
    },
  },
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
};
</script>
